package com.kinyx.framework.db;

import static com.kinyx.framework.db.Statics.Entity;

import java.util.Set;

import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

import com.kinyx.framework.processor.Processor;
import com.kinyx.framework.processor.Utils;

@SupportedAnnotationTypes({
		Entity
})
public class EntityProcessor extends Processor {

	@Override
	protected void doProcess(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
		final Set<? extends Element> elements = roundEnvironment.getRootElements();
		for (final Element element : elements) {
			if (!Utils.isClass(this.context, element)) { continue; } // 只处理Class类型的类型
			if (!Utils.containsAnnotation(this.context, element, Entity)) { continue; } // 只处理标注了javax.persistence.Entity注解的类型
			final TypeElement entityElement = TypeElement.class.cast(element);
			final String entityClassName = entityElement.getQualifiedName().toString();
			// 缓存过则跳过处理
			if (this.context.containsElement(entityClassName)) {
				this.context.getLogger().NOTE("EntityProcessor.doProcess -> TypeElement[" + entityElement + "] already cached");
				continue;
			}
			this.context.getLogger().NOTE("EntityProcessor.doProcess -> TypeElement[" + entityElement + "] create EntityTypeElement and cache");
			this.context.cacheElement(entityClassName, new EntityTypeElement(this.context, entityElement));// 没有缓存过则新建并缓存
		}

		// 生成资源文件
		this.context.getElements().forEach(entityTypeElement -> { EntityTypeElement.class.cast(entityTypeElement).generate(); });
	}

}
